package com.totem.product.controller;

import com.totem.base.constants.ErrorCode;
import com.totem.base.enums.ProductTypeEnum;
import com.totem.base.enums.SwitchEnum;
import com.totem.base.exception.BaseException;
import com.totem.base.model.PageVO;
import com.totem.base.model.Result;
import com.totem.base.mybatis.controller.BaseController;
import com.totem.product.api.ITProductServiceApi;
import com.totem.product.model.*;
import com.totem.product.service.ITProductsService;
import com.totem.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ProductController extends BaseController<ITProductsService, TProducts> implements ITProductServiceApi {
    @Override
    public Result<ProductVO> getInfoById(Long productId) {
        return Result.success(service.getInfoById(productId));
    }

    @Override
    public Result<PageVO<ProductVO>> productPage(ProductPageVO vo) {
        return Result.success(service.productPage(vo));
    }

    public Result uploadProduct(UploadProductFileVO vo) throws IOException {
        String coverPath = readydir("cover");
        String carouselPath = readydir("carousel");
        String videoPath = readydir("video");

        String coverFilename = vo.getCover().getOriginalFilename();
        String carouselFilename = vo.getCarousel()[0].getOriginalFilename();
        String videoFilename = vo.getVideo().getOriginalFilename();
        File coverDst = new File(coverPath+"/"+coverFilename);
        File carouselDst = new File(carouselPath+"/"+carouselFilename);
        File videoDst = new File(videoPath+"/"+videoFilename);

        vo.getCover().transferTo(coverDst);
        vo.getCarousel()[0].transferTo(carouselDst);
        vo.getVideo().transferTo(videoDst);
        return Result.success("上传文件成功");
    }

    private String readydir(String sub) throws IOException {
        String subPath = "/home/totem/temp/"+sub;
        File parent = new File(subPath);
        if(!parent.exists()){
            FileUtils.forceMkdir(parent);
        }
        return subPath;
    }
}
